import React, { Component } from 'react';
import { connect } from 'react-redux'
import store from './store'
import TodoListUI from './TodoListUI'

import {
  setListAction,
  changeInputAction,
  addItemAction,
  deleteItemAction
} from './store/actionCreators'

class TodoList extends Component {
  componentDidMount() {
    const action = setListAction([1, 2, 3])
    store.dispatch(action)
  }

  render() {
    // 解构赋值，代码清晰
    let { inputValue, changeInputValue, addItem, list, deleteItem } = this.props

    return (
      <TodoListUI
        inputValue={inputValue}
        changeInputValue={changeInputValue}
        addItem={addItem.bind(this)}
        list={list}
        deleteItem={deleteItem}
      />
    );
  }
}

// 转换state到props
const stateToProps = (state) => {
  return {
    inputValue: state.inputValue,
    list: state.list
  }
}

const dispatchToProps = (dispatch) => {
  return {
    changeInputValue(e) {
      dispatch(changeInputAction(e.target.value))
    },
    // 向列表添加一项
    addItem() {
      if (!this.props.inputValue) return
      dispatch(addItemAction())
    },
    // 删除一项
    deleteItem(index) {
      dispatch(deleteItemAction(index))
    }
  }
}

// 连接器
export default connect(stateToProps, dispatchToProps)(TodoList);